/**
 * Copyright (C) 2005-2009 Alfresco Software Limited.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

 * As a special exception to the terms and conditions of version 2.0 of 
 * the GPL, you may redistribute this Program in connection with Free/Libre 
 * and Open Source Software ("FLOSS") applications as described in Alfresco's 
 * FLOSS exception.  You should have recieved a copy of the text describing 
 * the FLOSS exception, and it is also available here: 
 * http://www.alfresco.com/legal/licensing
 */
 
if (typeof GWI == "undefined" || !GWI){
	var GWI = {};
} 
GWI.dashlet = GWI.dashlet || {};  

/**
 * Dashboard Site Tags component.
 * 
 * @namespace GWI
 * @class GWI.dashlet.RunChallenge
 */
(function()
{
	/**
	 * YUI Library aliases
	 */
	var 	Dom = YAHOO.util.Dom,
			Event = YAHOO.util.Event;

	/**
	 * Alfresco Slingshot aliases
	 */
	var 	$html = Alfresco.util.encodeHTML,
			$combine = Alfresco.util.combinePaths;

	/**
	 * RunHistory view constructor.
	 * 
	 * @param {String} htmlId The HTML id of the parent element
	 * @return {GWI.dashlet.RunHistory} The new component instance
	 * @constructor
	 */
	GWI.dashlet.RunHistory = function GWI_RunHistory_constructor(htmlId){
		return GWI.dashlet.RunHistory.superclass.constructor.call(this, "GWI.dashlet.RunHistory", htmlId);
	};

	/**
	 * Extend from Alfresco.component.Base and add class implementation
	 */
	YAHOO.extend(GWI.dashlet.RunHistory, Alfresco.component.Base,
	{
		/**
		 * Object container for initialization options
		 *
		 * @property options
		 * @type object
		 */
		options:
		{
			currentUser: null,
			currentRunType: "ALL"
		},
      
		/**
		 * Dom containing the run history
		 */
		bodyContainer : null,
      
		/**
		 * Fired by YUI when parent element is available for scripting
		 * @method onReady
		 */
		onReady: function GWI_RunHistory_onReady()
		{
			var me = this;
         
			// The body container
			this.bodyContainer = Dom.get(this.id);
			//this.showUserHistory();
			this.services.likes = new Alfresco.service.Ratings(Alfresco.service.Ratings.LIKES);
		},
  
		/**
		 * Show user history
		 * @method showUserHistory
		 */
		showUserHistory: function GWI_RunHistory_showUserHistory(username, runType)
		{
			// Hide the existing content
			Dom.setStyle(this.bodyContainer, "display", "none");
			// Make an AJAX request to the Tag Service REST API
	        var wsUrl = "/be/gwi/components/dashlets/run-challenge/user-history?";
	        if (username != null && username != "" && username != "CURRENT_USER"){
	        	wsUrl += "&username=" + username;
	        	this.options.currentUser = username;
	        }
	        else if(this.options.currentUser != null && username != "CURRENT_USER"){
	        	wsUrl += "&username=" + this.options.currentUser;	        	
	        }
			if (runType != null  && runType != ""){
	        	wsUrl += "&runType=" + runType;
	        	this.options.currentRunType = runType;
	        }
	        else if (this.options.currentRunType != null){
	        	wsUrl += "&runtype=" + this.options.currentRunType;	        	
	        }
			Alfresco.util.Ajax.jsonGet(
			{
				url: Alfresco.constants.URL_SERVICECONTEXT + wsUrl,
				successCallback:
				{
					fn: this.onShowUserHistorySuccess,
					scope: this
				},
				failureCallback:
				{
					fn: this.onShowUserHistoryFailed,
					scope: this
				},
				scope: this,
				noReloadOnAuthFailure: true
			});
		},
      
		/**
		 * Show history retrieved successfully
		 * @method onShowUserHistorySuccess
		 * @param p_response {object} Response object from request
		 */
		onShowUserHistorySuccess: function GWI_RunHistory_onShowUserHistorySuccess(p_response)
		{	
			var detailsHtml = p_response.serverResponse.responseText;
			this.bodyContainer.innerHTML = detailsHtml;
			this.bindActions();
			// Fade the new content in
			Alfresco.util.Anim.fadeIn(this.bodyContainer);
		},

		/**
		 * Show history request failed
		 * @method onShowUserHistoryFailed
		 */
		onShowUserHistoryFailed: function GWI_RunHistory_onShowUserHistoryFailed()
		{
			this.bodyContainer.innerHTML = this.msg("showUserHistory-failed");
			Alfresco.util.Anim.fadeIn(this.bodyContainer);
		},

	    /**
		 * Bind actions
		 * @method bindActions
		 */
		bindActions: function GWI_RunHistory_bindActions()
		{
			var likeRunActions = Dom.getElementsByClassName("likeRun");
			var unlikeRunActions = Dom.getElementsByClassName("unlikeRun");
			
			Event.addListener(likeRunActions, "click", function(e) {
				var nodeRefString = e.currentTarget.parentNode.parentNode.parentNode.attributes.nodeRef.value;
				var nodeRef = new Alfresco.util.NodeRef(nodeRefString);
		         var responseConfig =
		         {
		            successCallback:
		            {
		               fn: function GWI_RunHistory_onLikes_success(event, p_nodeRef)
		               {
		                  var data = event.json.data;
		                  if (data)
		                  {
		                     this.showUserHistory();
		                  }
		               },
		               scope: this,
		               obj: nodeRef.toString()
		            },
		            failureCallback:
		            {
		               fn: function GWI_RunHistory_onLikes_failure(event, p_nodeRef)
		               {
		                  Alfresco.util.PopupManager.displayPrompt(
		                  {
		                     text: this.msg("message.save.failure")
		                  });
		               },
		               scope: this,
		               obj: nodeRef.toString()
		            }
		         };

				this.services.likes.set(nodeRef, 1, responseConfig);

			}, this, true);

			Event.addListener(unlikeRunActions, "click", function(e) {
				var nodeRefString = e.currentTarget.parentNode.parentNode.parentNode.attributes.nodeRef.value;
				var nodeRef = new Alfresco.util.NodeRef(nodeRefString);
		         var responseConfig =
		         {
		            successCallback:
		            {
		               fn: function GWI_RunHistory_onLikes_success(event, p_nodeRef)
		               {
		                  var data = event.json.data;
		                  if (data)
		                  {
		                     this.showUserHistory();
		                  }
		               },
		               scope: this,
		               obj: nodeRef.toString()
		            },
		            failureCallback:
		            {
		               fn: function GWI_RunHistory_onLikes_failure(event, p_nodeRef)
		               {
		                  Alfresco.util.PopupManager.displayPrompt(
		                  {
		                     text: this.msg("message.save.failure")
		                  });
		               },
		               scope: this,
		               obj: nodeRef.toString()
		            }
		         };

				this.services.likes.remove(nodeRef, responseConfig);

			}, this, true);
			
		}
	});
})();
